

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Porting Python 2 Code to Python 3 &mdash; Python v2.7.8 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7.8',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7.8 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7.8 documentation" href="../index.html" />
    <link rel="up" title="Python HOWTOs" href="index.html" />
    <link rel="next" title="Porting Extension Modules to Python 3" href="cporting.html" />
    <link rel="prev" title="Python HOWTOs" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python HOWTOs"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" accesskey="U">Python HOWTOs</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="porting-python-2-code-to-python-3">
<span id="pyporting-howto"></span><h1>Porting Python 2 Code to Python 3<a class="headerlink" href="#porting-python-2-code-to-python-3" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">author:</th><td class="field-body">Brett Cannon</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>With Python 3 being the future of Python while Python 2 is still in active
use, it is good to have your project available for both major releases of
Python. This guide is meant to help you figure out how best to support both
Python 2 &amp; 3 simultaneously.</p>
<p>If you are looking to port an extension module instead of pure Python code,
please see <a class="reference internal" href="cporting.html#cporting-howto"><em>Porting Extension Modules to Python 3</em></a>.</p>
<p>If you would like to read one core Python developer&#8217;s take on why Python 3
came into existence, you can read Nick Coghlan&#8217;s <a class="reference external" href="http://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html">Python 3 Q &amp; A</a>.</p>
<p>If you prefer to read a (free) book on porting a project to Python 3,
consider reading <a class="reference external" href="http://python3porting.com/">Porting to Python 3</a> by Lennart Regebro which should cover
much of what is discussed in this HOWTO.</p>
<p>For help with porting, you can email the <a class="reference external" href="http://mail.python.org/mailman/listinfo/python-porting">python-porting</a> mailing list with
questions.</p>
</div>
<div class="section" id="the-short-version">
<h2>The Short Version<a class="headerlink" href="#the-short-version" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>Decide what&#8217;s the oldest version of Python 2 you want to support (if at all)</li>
<li>Make sure you have a thorough test suite and use continuous integration
testing to make sure you stay compatible with the versions of Python you care
about</li>
<li>If you have dependencies, check their Python 3 status using caniusepython3
(<a class="reference external" href="https://pypi.python.org/pypi/caniusepython3">command-line tool</a>,
<a class="reference external" href="https://caniusepython3.com/">web app</a>)</li>
</ul>
<p>With that done, your options are:</p>
<ul class="simple">
<li>If you are dropping Python 2 support, use <a class="reference external" href="http://docs.python.org/2/library/2to3.html">2to3</a> to port to Python 3</li>
<li>If you are keeping Python 2 support, then start writing Python 2/3-compatible
code starting <strong>TODAY</strong><ul>
<li>If you have dependencies that have not been ported, reach out to them to port
their project while working to make your code compatible with Python 3 so
you&#8217;re ready when your dependencies are all ported</li>
<li>If all your dependencies have been ported (or you have none), go ahead and
port to Python 3</li>
</ul>
</li>
<li>If you are creating a new project that wants to have 2/3 compatibility,
code in Python 3 and then backport to Python 2</li>
</ul>
</div>
<div class="section" id="before-you-begin">
<h2>Before You Begin<a class="headerlink" href="#before-you-begin" title="Permalink to this headline">¶</a></h2>
<p>If your project is on the <a class="reference external" href="http://pypi.python.org/">Cheeseshop</a>/<a class="reference external" href="http://pypi.python.org/">PyPI</a>, make sure it has the proper
<a class="reference external" href="https://pypi.python.org/pypi?%3Aaction=list_classifiers">trove classifiers</a> to signify what versions of Python it <strong>currently</strong>
supports. At minimum you should specify the major version(s), e.g.
<tt class="docutils literal"><span class="pre">Programming</span> <span class="pre">Language</span> <span class="pre">::</span> <span class="pre">Python</span> <span class="pre">::</span> <span class="pre">2</span></tt> if your project currently only supports
Python 2. It is preferrable that you be as specific as possible by listing every
major/minor version of Python that you support, e.g. if your project supports
Python 2.6 and 2.7, then you want the classifiers of:</p>
<div class="highlight-python"><pre>Programming Language :: Python :: 2
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7</pre>
</div>
<p>Once your project supports Python 3 you will want to go back and add the
appropriate classifiers for Python 3 as well. This is important as setting the
<tt class="docutils literal"><span class="pre">Programming</span> <span class="pre">Language</span> <span class="pre">::</span> <span class="pre">Python</span> <span class="pre">::</span> <span class="pre">3</span></tt> classifier will lead to your project
being listed under the <a class="reference external" href="https://pypi.python.org/pypi?:action=browse&amp;c=533&amp;show=all">Python 3 Packages</a> section of PyPI.</p>
<p>Make sure you have a robust test suite. You need to
make sure everything continues to work, just like when you support a new
minor/feature release of Python. This means making sure your test suite is
thorough and is ported properly between Python 2 &amp; 3 (consider using <a class="reference external" href="https://pypi.python.org/pypi/coverage">coverage</a>
to measure that you have effective test coverage). You will also most likely
want to use something like <a class="reference external" href="https://pypi.python.org/pypi/tox">tox</a> to automate testing between all of your
supported versions of Python. You will also want to <strong>port your tests first</strong> so
that you can make sure that you detect breakage during the transition. Tests also
tend to be simpler than the code they are testing so it gives you an idea of how
easy it can be to port code.</p>
<p>Drop support for older Python versions if possible. <a class="reference external" href="http://www.python.org/2.5.x">Python 2.5</a>
introduced a lot of useful syntax and libraries which have become idiomatic
in Python 3. <a class="reference external" href="http://www.python.org/2.6.x">Python 2.6</a> introduced future statements which makes
compatibility much easier if you are going from Python 2 to 3.
<a class="reference external" href="http://www.python.org/2.7.x">Python 2.7</a> continues the trend in the stdlib. Choose the newest version
of Python which you believe can be your minimum support version
and work from there.</p>
<p>Target the newest version of Python 3 that you can. Beyond just the usual
bugfixes, compatibility has continued to improve between Python 2 and 3 as time
has passed. E.g. Python 3.3 added back the <tt class="docutils literal"><span class="pre">u</span></tt> prefix for
strings, making source-compatible Python code easier to write.</p>
</div>
<div class="section" id="writing-source-compatible-python-2-3-code">
<h2>Writing Source-Compatible Python 2/3 Code<a class="headerlink" href="#writing-source-compatible-python-2-3-code" title="Permalink to this headline">¶</a></h2>
<p>Over the years the Python community has discovered that the easiest way to
support both Python 2 and 3 in parallel is to write Python code that works in
either version. While this might sound counter-intuitive at first, it actually
is not difficult and typically only requires following some select
(non-idiomatic) practices and using some key projects to help make bridging
between Python 2 and 3 easier.</p>
<div class="section" id="projects-to-consider">
<h3>Projects to Consider<a class="headerlink" href="#projects-to-consider" title="Permalink to this headline">¶</a></h3>
<p>The lowest level library for supporting Python 2 &amp; 3 simultaneously is <a class="reference external" href="https://pypi.python.org/pypi/six">six</a>.
Reading through its documentation will give you an idea of where exactly the
Python language changed between versions 2 &amp; 3 and thus what you will want the
library to help you continue to support.</p>
<p>To help automate porting your code over to using six, you can use
<a class="reference external" href="https://github.com/mitsuhiko/python-modernize">modernize</a>. This project will attempt to rewrite your code to be as modern as
possible while using six to smooth out any differences between Python 2 &amp; 3.</p>
<p>If you want to write your compatible code to feel more like Python 3 there is
the <a class="reference external" href="http://python-future.org/">future</a> project. It tries to provide backports of objects from Python 3 so
that you can use them from Python 2-compatible code, e.g. replacing the
<tt class="docutils literal"><span class="pre">bytes</span></tt> type from Python 2 with the one from Python 3.
It also provides a translation script like modernize (its translation code is
actually partially based on it) to help start working with a pre-existing code
base. It is also unique in that its translation script will also port Python 3
code backwards as well as Python 2 code forwards.</p>
</div>
<div class="section" id="tips-tricks">
<h3>Tips &amp; Tricks<a class="headerlink" href="#tips-tricks" title="Permalink to this headline">¶</a></h3>
<p>To help with writing source-compatible code using one of the projects mentioned
in <a class="reference internal" href="#projects-to-consider">Projects to Consider</a>, consider following the below suggestions. Some of
them are handled by the suggested projects, so if you do use one of them then
read their documentation first to see which suggestions below will taken care of
for you.</p>
<div class="section" id="support-python-2-7">
<h4>Support Python 2.7<a class="headerlink" href="#support-python-2-7" title="Permalink to this headline">¶</a></h4>
<p>As a first step, make sure that your project is compatible with <a class="reference external" href="http://www.python.org/2.7.x">Python 2.7</a>.
This is just good to do as Python 2.7 is the last release of Python 2 and thus
will be used for a rather long time. It also allows for use of the <tt class="docutils literal"><span class="pre">-3</span></tt> flag
to Python to help discover places in your code where compatibility might be an
issue (the <tt class="docutils literal"><span class="pre">-3</span></tt> flag is in Python 2.6 but Python 2.7 adds more warnings).</p>
</div>
<div class="section" id="try-to-support-python-2-6-and-newer-only">
<h4>Try to Support <a class="reference external" href="http://www.python.org/2.6.x">Python 2.6</a> and Newer Only<a class="headerlink" href="#try-to-support-python-2-6-and-newer-only" title="Permalink to this headline">¶</a></h4>
<p>While not possible for all projects, if you can support <a class="reference external" href="http://www.python.org/2.6.x">Python 2.6</a> and newer
<strong>only</strong>, your life will be much easier. Various future statements, stdlib
additions, etc. exist only in Python 2.6 and later which greatly assist in
supporting Python 3. But if you project must keep support for <a class="reference external" href="http://www.python.org/2.5.x">Python 2.5</a> then
it is still possible to simultaneously support Python 3.</p>
<p>Below are the benefits you gain if you only have to support Python 2.6 and
newer. Some of these options are personal choice while others are
<strong>strongly</strong> recommended (the ones that are more for personal choice are
labeled as such).  If you continue to support older versions of Python then you
at least need to watch out for situations that these solutions fix and handle
them appropriately (which is where library help from e.g. <a class="reference external" href="https://pypi.python.org/pypi/six">six</a> comes in handy).</p>
<div class="section" id="from-future-import-print-function">
<h5><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">print_function</span></tt><a class="headerlink" href="#from-future-import-print-function" title="Permalink to this headline">¶</a></h5>
<p>It will not only get you used to typing <tt class="docutils literal"><span class="pre">print()</span></tt> as a function instead of a
statement, but it will also give you the various benefits the function has over
the Python 2 statement (<a class="reference external" href="https://pypi.python.org/pypi/six">six</a> provides a function if you support Python 2.5 or
older).</p>
</div>
<div class="section" id="from-future-import-unicode-literals">
<h5><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">unicode_literals</span></tt><a class="headerlink" href="#from-future-import-unicode-literals" title="Permalink to this headline">¶</a></h5>
<p>If you choose to use this future statement then all string literals in
Python 2 will be assumed to be Unicode (as is already the case in Python 3).
If you choose not to use this future statement then you should mark all of your
text strings with a <tt class="docutils literal"><span class="pre">u</span></tt> prefix and only support Python 3.3 or newer. But you
are <strong>strongly</strong> advised to do one or the other (<a class="reference external" href="https://pypi.python.org/pypi/six">six</a> provides a function in
case you don&#8217;t want to use the future statement <strong>and</strong> you want to support
Python 3.2 or older).</p>
</div>
<div class="section" id="bytes-string-literals">
<h5>Bytes/string literals<a class="headerlink" href="#bytes-string-literals" title="Permalink to this headline">¶</a></h5>
<p>This is a <strong>very</strong> important one. Prefix Python 2 strings that
are meant to contain bytes with a <tt class="docutils literal"><span class="pre">b</span></tt> prefix to very clearly delineate
what is and is not a Python 3 text string (<a class="reference external" href="https://pypi.python.org/pypi/six">six</a> provides a function to use for
Python 2.5 compatibility).</p>
<p>This point cannot be stressed enough: make sure you know what all of your string
literals in Python 2 are meant to be in Python 3. Any string literal that
should be treated as bytes should have the <tt class="docutils literal"><span class="pre">b</span></tt> prefix. Any string literal
that should be Unicode/text in Python 2 should either have the <tt class="docutils literal"><span class="pre">u</span></tt> literal
(supported, but ignored, in Python 3.3 and later) or you should have
<tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">unicode_literals</span></tt> at the top of the file. But the key
point is you should know how Python 3 will treat every one one of your string
literals and you should mark them as appropriate.</p>
<p>There are some differences between byte literals in Python 2 and those in
Python 3 thanks to the bytes type just being an alias to <tt class="docutils literal"><span class="pre">str</span></tt> in Python 2.
See the <a class="reference internal" href="#handle-common-gotchas">Handle Common &#8220;Gotchas&#8221;</a> section for what to watch out for.</p>
</div>
<div class="section" id="from-future-import-absolute-import">
<h5><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></tt><a class="headerlink" href="#from-future-import-absolute-import" title="Permalink to this headline">¶</a></h5>
<p>Discussed in more detail below, but you should use this future statement to
prevent yourself from accidentally using implicit relative imports.</p>
</div>
</div>
<div class="section" id="supporting-python-2-5-and-newer-only">
<h4>Supporting <a class="reference external" href="http://www.python.org/2.5.x">Python 2.5</a> and Newer Only<a class="headerlink" href="#supporting-python-2-5-and-newer-only" title="Permalink to this headline">¶</a></h4>
<p>If you are supporting <a class="reference external" href="http://www.python.org/2.5.x">Python 2.5</a> and newer there are still some features of
Python that you can utilize.</p>
<div class="section" id="id1">
<h5><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></tt><a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h5>
<p>Implicit relative imports (e.g., importing <tt class="docutils literal"><span class="pre">spam.bacon</span></tt> from within
<tt class="docutils literal"><span class="pre">spam.eggs</span></tt> with the statement <tt class="docutils literal"><span class="pre">import</span> <span class="pre">bacon</span></tt>) do not work in Python 3.
This future statement moves away from that and allows the use of explicit
relative imports (e.g., <tt class="docutils literal"><span class="pre">from</span> <span class="pre">.</span> <span class="pre">import</span> <span class="pre">bacon</span></tt>).</p>
<p>In <a class="reference external" href="http://www.python.org/2.5.x">Python 2.5</a> you must use
the __future__ statement to get to use explicit relative imports and prevent
implicit ones. In <a class="reference external" href="http://www.python.org/2.6.x">Python 2.6</a> explicit relative imports are available without
the statement, but you still want the __future__ statement to prevent implicit
relative imports. In <a class="reference external" href="http://www.python.org/2.7.x">Python 2.7</a> the __future__ statement is not needed. In
other words, unless you are only supporting Python 2.7 or a version earlier
than Python 2.5, use this __future__ statement.</p>
</div>
<div class="section" id="mark-all-unicode-strings-with-a-u-prefix">
<h5>Mark all Unicode strings with a <tt class="docutils literal"><span class="pre">u</span></tt> prefix<a class="headerlink" href="#mark-all-unicode-strings-with-a-u-prefix" title="Permalink to this headline">¶</a></h5>
<p>While Python 2.6 has a <tt class="docutils literal"><span class="pre">__future__</span></tt> statement to automatically cause Python 2
to treat all string literals as Unicode, Python 2.5 does not have that shortcut.
This means you should go through and mark all string literals with a <tt class="docutils literal"><span class="pre">u</span></tt>
prefix to turn them explicitly into text strings where appropriate and only
support Python 3.3 or newer. Otherwise use a project like <a class="reference external" href="https://pypi.python.org/pypi/six">six</a> which provides a
function to pass all text string literals through.</p>
</div>
<div class="section" id="capturing-the-currently-raised-exception">
<h5>Capturing the Currently Raised Exception<a class="headerlink" href="#capturing-the-currently-raised-exception" title="Permalink to this headline">¶</a></h5>
<p>In Python 2.5 and earlier the syntax to access the current exception is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
  <span class="k">raise</span> <span class="ne">Exception</span><span class="p">()</span>
<span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">exc</span><span class="p">:</span>
  <span class="c"># Current exception is &#39;exc&#39;.</span>
  <span class="k">pass</span>
</pre></div>
</div>
<p>This syntax changed in Python 3 (and backported to <a class="reference external" href="http://www.python.org/2.6.x">Python 2.6</a> and later)
to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
  <span class="k">raise</span> <span class="ne">Exception</span><span class="p">()</span>
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
  <span class="c"># Current exception is &#39;exc&#39;.</span>
  <span class="c"># In Python 3, &#39;exc&#39; is restricted to the block; in Python 2.6/2.7 it will &quot;leak&quot;.</span>
  <span class="k">pass</span>
</pre></div>
</div>
<p>Because of this syntax change you must change how you capture the current
exception in Python 2.5 and earlier to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
  <span class="k">raise</span> <span class="ne">Exception</span><span class="p">()</span>
<span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
  <span class="kn">import</span> <span class="nn">sys</span>
  <span class="n">exc</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()[</span><span class="mi">1</span><span class="p">]</span>
  <span class="c"># Current exception is &#39;exc&#39;.</span>
  <span class="k">pass</span>
</pre></div>
</div>
<p>You can get more information about the raised exception from
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a> than simply the current exception instance, but you most
likely don&#8217;t need it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>In Python 3, the traceback is attached to the exception instance
through the <tt class="docutils literal"><span class="pre">__traceback__</span></tt> attribute. If the instance is saved in
a local variable that persists outside of the <tt class="docutils literal"><span class="pre">except</span></tt> block, the
traceback will create a reference cycle with the current frame and its
dictionary of local variables.  This will delay reclaiming dead
resources until the next cyclic <a class="reference internal" href="../glossary.html#term-garbage-collection"><em class="xref std std-term">garbage collection</em></a> pass.</p>
<p class="last">In Python 2, this problem only occurs if you save the traceback itself
(e.g. the third element of the tuple returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>)
in a variable.</p>
</div>
</div>
</div>
<div class="section" id="handle-common-gotchas">
<h4>Handle Common &#8220;Gotchas&#8221;<a class="headerlink" href="#handle-common-gotchas" title="Permalink to this headline">¶</a></h4>
<p>These are things to watch out for no matter what version of Python 2 you are
supporting which are not syntactic considerations.</p>
<div class="section" id="from-future-import-division">
<h5><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></tt><a class="headerlink" href="#from-future-import-division" title="Permalink to this headline">¶</a></h5>
<p>While the exact same outcome can be had by using the <tt class="docutils literal"><span class="pre">-Qnew</span></tt> argument to
Python, using this future statement lifts the requirement that your users use
the flag to get the expected behavior of division in Python 3
(e.g., <tt class="docutils literal"><span class="pre">1/2</span> <span class="pre">==</span> <span class="pre">0.5;</span> <span class="pre">1//2</span> <span class="pre">==</span> <span class="pre">0</span></tt>).</p>
</div>
<div class="section" id="specify-when-opening-a-file-as-binary">
<h5>Specify when opening a file as binary<a class="headerlink" href="#specify-when-opening-a-file-as-binary" title="Permalink to this headline">¶</a></h5>
<p>Unless you have been working on Windows, there is a chance you have not always
bothered to add the <tt class="docutils literal"><span class="pre">b</span></tt> mode when opening a binary file (e.g., <tt class="docutils literal"><span class="pre">rb</span></tt> for
binary reading).  Under Python 3, binary files and text files are clearly
distinct and mutually incompatible; see the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><tt class="xref py py-mod docutils literal"><span class="pre">io</span></tt></a> module for details.
Therefore, you <strong>must</strong> make a decision of whether a file will be used for
binary access (allowing to read and/or write bytes data) or text access
(allowing to read and/or write unicode data).</p>
</div>
<div class="section" id="text-files">
<h5>Text files<a class="headerlink" href="#text-files" title="Permalink to this headline">¶</a></h5>
<p>Text files created using <tt class="docutils literal"><span class="pre">open()</span></tt> under Python 2 return byte strings,
while under Python 3 they return unicode strings.  Depending on your porting
strategy, this can be an issue.</p>
<p>If you want text files to return unicode strings in Python 2, you have two
possibilities:</p>
<ul class="simple">
<li>Under Python 2.6 and higher, use <a class="reference internal" href="../library/io.html#io.open" title="io.open"><tt class="xref py py-func docutils literal"><span class="pre">io.open()</span></tt></a>.  Since <a class="reference internal" href="../library/io.html#io.open" title="io.open"><tt class="xref py py-func docutils literal"><span class="pre">io.open()</span></tt></a>
is essentially the same function in both Python 2 and Python 3, it will
help iron out any issues that might arise.</li>
<li>If pre-2.6 compatibility is needed, then you should use <a class="reference internal" href="../library/codecs.html#codecs.open" title="codecs.open"><tt class="xref py py-func docutils literal"><span class="pre">codecs.open()</span></tt></a>
instead.  This will make sure that you get back unicode strings in Python 2.</li>
</ul>
</div>
<div class="section" id="subclass-object">
<h5>Subclass <tt class="docutils literal"><span class="pre">object</span></tt><a class="headerlink" href="#subclass-object" title="Permalink to this headline">¶</a></h5>
<p>New-style classes have been around since <a class="reference external" href="http://www.python.org/2.2.x">Python 2.2</a>. You need to make sure
you are subclassing from <tt class="docutils literal"><span class="pre">object</span></tt> to avoid odd edge cases involving method
resolution order, etc. This continues to be totally valid in Python 3 (although
unneeded as all classes implicitly inherit from <tt class="docutils literal"><span class="pre">object</span></tt>).</p>
</div>
<div class="section" id="deal-with-the-bytes-string-dichotomy">
<h5>Deal With the Bytes/String Dichotomy<a class="headerlink" href="#deal-with-the-bytes-string-dichotomy" title="Permalink to this headline">¶</a></h5>
<p>One of the biggest issues people have when porting code to Python 3 is handling
the bytes/string dichotomy. Because Python 2 allowed the <tt class="docutils literal"><span class="pre">str</span></tt> type to hold
textual data, people have over the years been rather loose in their delineation
of what <tt class="docutils literal"><span class="pre">str</span></tt> instances held text compared to bytes. In Python 3 you cannot
be so care-free anymore and need to properly handle the difference. The key to
handling this issue is to make sure that <strong>every</strong> string literal in your
Python 2 code is either syntactically or functionally marked as either bytes or
text data. After this is done you then need to make sure your APIs are designed
to either handle a specific type or made to be properly polymorphic.</p>
<div class="section" id="mark-up-python-2-string-literals">
<h6>Mark Up Python 2 String Literals<a class="headerlink" href="#mark-up-python-2-string-literals" title="Permalink to this headline">¶</a></h6>
<p>First thing you must do is designate every single string literal in Python 2
as either textual or bytes data. If you are only supporting Python 2.6 or
newer, this can be accomplished by marking bytes literals with a <tt class="docutils literal"><span class="pre">b</span></tt> prefix
and then designating textual data with a <tt class="docutils literal"><span class="pre">u</span></tt> prefix or using the
<tt class="docutils literal"><span class="pre">unicode_literals</span></tt> future statement.</p>
<p>If your project supports versions of Python predating 2.6, then you should use
the <a class="reference external" href="https://pypi.python.org/pypi/six">six</a> project and its <tt class="docutils literal"><span class="pre">b()</span></tt> function to denote bytes literals. For text
literals you can either use six&#8217;s <tt class="docutils literal"><span class="pre">u()</span></tt> function or use a <tt class="docutils literal"><span class="pre">u</span></tt> prefix.</p>
</div>
<div class="section" id="decide-what-apis-will-accept">
<h6>Decide what APIs Will Accept<a class="headerlink" href="#decide-what-apis-will-accept" title="Permalink to this headline">¶</a></h6>
<p>In Python 2 it was very easy to accidentally create an API that accepted both
bytes and textual data. But in Python 3, thanks to the more strict handling of
disparate types, this loose usage of bytes and text together tends to fail.</p>
<p>Take the dict <tt class="docutils literal"><span class="pre">{b'a':</span> <span class="pre">'bytes',</span> <span class="pre">u'a':</span> <span class="pre">'text'}</span></tt> in Python 2.6. It creates the
dict <tt class="docutils literal"><span class="pre">{u'a':</span> <span class="pre">'text'}</span></tt> since <tt class="docutils literal"><span class="pre">b'a'</span> <span class="pre">==</span> <span class="pre">u'a'</span></tt>. But in Python 3 the equivalent
dict creates <tt class="docutils literal"><span class="pre">{b'a':</span> <span class="pre">'bytes',</span> <span class="pre">'a':</span> <span class="pre">'text'}</span></tt>, i.e., no lost data. Similar
issues can crop up when transitioning Python 2 code to Python 3.</p>
<p>This means you need to choose what an API is going to accept and create and
consistently stick to that API in both Python 2 and 3.</p>
</div>
<div class="section" id="bytes-unicode-comparison">
<h6>Bytes / Unicode Comparison<a class="headerlink" href="#bytes-unicode-comparison" title="Permalink to this headline">¶</a></h6>
<p>In Python 3, mixing bytes and unicode is forbidden in most situations; it
will raise a <tt class="xref py py-class docutils literal"><span class="pre">TypeError</span></tt> where Python 2 would have attempted an implicit
coercion between types.  However, there is one case where it doesn&#8217;t and
it can be very misleading:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&quot;&quot;</span> <span class="o">==</span> <span class="s">&quot;&quot;</span>
<span class="go">False</span>
</pre></div>
</div>
<p>This is because an equality comparison is required by the language to always
succeed (and return <tt class="xref docutils literal"><span class="pre">False</span></tt> for incompatible types).  However, this also
means that code incorrectly ported to Python 3 can display buggy behaviour
if such comparisons are silently executed.  To detect such situations,
Python 3 has a <tt class="docutils literal"><span class="pre">-b</span></tt> flag that will display a warning:</p>
<div class="highlight-python"><pre>$ python3 -b
&gt;&gt;&gt; b"" == ""
__main__:1: BytesWarning: Comparison between bytes and string
False</pre>
</div>
<p>To turn the warning into an exception, use the <tt class="docutils literal"><span class="pre">-bb</span></tt> flag instead:</p>
<div class="highlight-python"><pre>$ python3 -bb
&gt;&gt;&gt; b"" == ""
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
BytesWarning: Comparison between bytes and string</pre>
</div>
</div>
</div>
<div class="section" id="indexing-bytes-objects">
<h5>Indexing bytes objects<a class="headerlink" href="#indexing-bytes-objects" title="Permalink to this headline">¶</a></h5>
<p>Another potentially surprising change is the indexing behaviour of bytes
objects in Python 3:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&quot;xyz&quot;</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">120</span>
</pre></div>
</div>
<p>Indeed, Python 3 bytes objects (as well as <a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><tt class="xref py py-class docutils literal"><span class="pre">bytearray</span></tt></a> objects)
are sequences of integers.  But code converted from Python 2 will often
assume that indexing a bytestring produces another bytestring, not an
integer.  To reconcile both behaviours, use slicing:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&quot;xyz&quot;</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">1</span><span class="p">]</span>
<span class="go">b&#39;x&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&quot;xyz&quot;</span><span class="p">[</span><span class="n">n</span><span class="p">:</span><span class="n">n</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span>
<span class="go">b&#39;y&#39;</span>
</pre></div>
</div>
<p>The only remaining gotcha is that an out-of-bounds slice returns an empty
bytes object instead of raising <tt class="docutils literal"><span class="pre">IndexError</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&quot;xyz&quot;</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
<span class="nc">IndexError</span>: <span class="n-Identifier">index out of range</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="s">&quot;xyz&quot;</span><span class="p">[</span><span class="mi">3</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span>
<span class="go">b&#39;&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="str-unicode">
<h5><tt class="docutils literal"><span class="pre">__str__()</span></tt>/<tt class="docutils literal"><span class="pre">__unicode__()</span></tt><a class="headerlink" href="#str-unicode" title="Permalink to this headline">¶</a></h5>
<p>In Python 2, objects can specify both a string and unicode representation of
themselves. In Python 3, though, there is only a string representation. This
becomes an issue as people can inadvertently do things in their <tt class="docutils literal"><span class="pre">__str__()</span></tt>
methods which have unpredictable results (e.g., infinite recursion if you
happen to use the <tt class="docutils literal"><span class="pre">unicode(self).encode('utf8')</span></tt> idiom as the body of your
<tt class="docutils literal"><span class="pre">__str__()</span></tt> method).</p>
<p>You can use a mixin class to work around this. This allows you to only define a
<tt class="docutils literal"><span class="pre">__unicode__()</span></tt> method for your class and let the mixin derive
<tt class="docutils literal"><span class="pre">__str__()</span></tt> for you (code from
<a class="reference external" href="http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/">http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/</a>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sys</span>

<span class="k">class</span> <span class="nc">UnicodeMixin</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>

  <span class="sd">&quot;&quot;&quot;Mixin class to handle defining the proper __str__/__unicode__</span>
<span class="sd">  methods in Python 2 or 3.&quot;&quot;&quot;</span>

  <span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&gt;=</span> <span class="mi">3</span><span class="p">:</span> <span class="c"># Python 3</span>
      <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
          <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__unicode__</span><span class="p">()</span>
  <span class="k">else</span><span class="p">:</span>  <span class="c"># Python 2</span>
      <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
          <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__unicode__</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">&#39;utf8&#39;</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">Spam</span><span class="p">(</span><span class="n">UnicodeMixin</span><span class="p">):</span>

  <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
      <span class="k">return</span> <span class="s">u&#39;spam-spam-bacon-spam&#39;</span>  <span class="c"># 2to3 will remove the &#39;u&#39; prefix</span>
</pre></div>
</div>
</div>
<div class="section" id="don-t-index-on-exceptions">
<h5>Don&#8217;t Index on Exceptions<a class="headerlink" href="#don-t-index-on-exceptions" title="Permalink to this headline">¶</a></h5>
<p>In Python 2, the following worked:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">exc</span> <span class="o">=</span> <span class="ne">Exception</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">exc</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">exc</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>  <span class="c"># Python 2 only!</span>
<span class="go">2</span>
</pre></div>
</div>
<p>But in Python 3, indexing directly on an exception is an error. You need to
make sure to only index on the <tt class="xref py py-attr docutils literal"><span class="pre">BaseException.args</span></tt> attribute which is a
sequence containing all arguments passed to the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method.</p>
<p>Even better is to use the documented attributes the exception provides.</p>
</div>
<div class="section" id="don-t-use-getslice-friends">
<h5>Don&#8217;t use <tt class="docutils literal"><span class="pre">__getslice__</span></tt> &amp; Friends<a class="headerlink" href="#don-t-use-getslice-friends" title="Permalink to this headline">¶</a></h5>
<p>Been deprecated for a while, but Python 3 finally drops support for
<tt class="docutils literal"><span class="pre">__getslice__()</span></tt>, etc. Move completely over to <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> and
friends.</p>
</div>
<div class="section" id="updating-doctests">
<h5>Updating doctests<a class="headerlink" href="#updating-doctests" title="Permalink to this headline">¶</a></h5>
<p>Don&#8217;t forget to make them Python 2/3 compatible as well. If you wrote a
monolithic set of doctests (e.g., a single docstring containing all of your
doctests), you should at least consider breaking the doctests up into smaller
pieces to make it more manageable to fix. Otherwise it might very well be worth
your time and effort to port your tests to <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><tt class="xref py py-mod docutils literal"><span class="pre">unittest</span></tt></a>.</p>
</div>
<div class="section" id="update-map-for-imbalanced-input-sequences">
<h5>Update <tt class="docutils literal"><span class="pre">map</span></tt> for imbalanced input sequences<a class="headerlink" href="#update-map-for-imbalanced-input-sequences" title="Permalink to this headline">¶</a></h5>
<p>With Python 2, when <tt class="docutils literal"><span class="pre">map</span></tt> was given more than one input sequence it would pad
the shorter sequences with <cite>None</cite> values, returning a sequence as long as the
longest input sequence.</p>
<p>With Python 3, if the input sequences to <tt class="docutils literal"><span class="pre">map</span></tt> are of unequal length, <tt class="docutils literal"><span class="pre">map</span></tt>
will stop at the termination of the shortest of the sequences. For full
compatibility with <tt class="docutils literal"><span class="pre">map</span></tt> from Python 2.x, wrap the sequence arguments in
<tt class="xref py py-func docutils literal"><span class="pre">itertools.zip_longest()</span></tt>, e.g. <tt class="docutils literal"><span class="pre">map(func,</span> <span class="pre">*sequences)</span></tt> becomes
<tt class="docutils literal"><span class="pre">list(map(func,</span> <span class="pre">itertools.zip_longest(*sequences)))</span></tt>.</p>
</div>
</div>
</div>
<div class="section" id="eliminate-3-warnings">
<h3>Eliminate <tt class="docutils literal"><span class="pre">-3</span></tt> Warnings<a class="headerlink" href="#eliminate-3-warnings" title="Permalink to this headline">¶</a></h3>
<p>When you run your application&#8217;s test suite, run it using the <tt class="docutils literal"><span class="pre">-3</span></tt> flag passed
to Python. This will cause various warnings to be raised during execution about
things that are semantic changes between Python 2 and 3. Try to eliminate those
warnings to make your code even more portable to Python 3.</p>
</div>
</div>
<div class="section" id="alternative-approaches">
<h2>Alternative Approaches<a class="headerlink" href="#alternative-approaches" title="Permalink to this headline">¶</a></h2>
<p>While supporting Python 2 &amp; 3 simultaneously is typically the preferred choice
by people so that they can continue to improve code and have it work for the
most number of users, your life may be easier if you only have to support one
major version of Python going forward.</p>
<div class="section" id="supporting-only-python-3-going-forward-from-python-2-code">
<h3>Supporting Only Python 3 Going Forward From Python 2 Code<a class="headerlink" href="#supporting-only-python-3-going-forward-from-python-2-code" title="Permalink to this headline">¶</a></h3>
<p>If you have Python 2 code but going forward only want to improve it as Python 3
code, then you can use <a class="reference external" href="http://docs.python.org/2/library/2to3.html">2to3</a> to translate your Python 2 code to Python 3 code.
This is only recommended, though, if your current version of your project is
going into maintenance mode and you want all new features to be exclusive to
Python 3.</p>
</div>
<div class="section" id="backporting-python-3-code-to-python-2">
<h3>Backporting Python 3 code to Python 2<a class="headerlink" href="#backporting-python-3-code-to-python-2" title="Permalink to this headline">¶</a></h3>
<p>If you have Python 3 code and have little interest in supporting Python 2 you
can use <a class="reference external" href="https://pypi.python.org/pypi/3to2">3to2</a> to translate from Python 3 code to Python 2 code. This is only
recommended if you don&#8217;t plan to heavily support Python 2 users. Otherwise
write your code for Python 3 and then backport as far back as you want. This
is typically easier than going from Python 2 to 3 as you will have worked out
any difficulties with e.g. bytes/strings, etc.</p>
</div>
</div>
<div class="section" id="other-resources">
<h2>Other Resources<a class="headerlink" href="#other-resources" title="Permalink to this headline">¶</a></h2>
<p>The authors of the following blog posts, wiki pages, and books deserve special
thanks for making public their tips for porting Python 2 code to Python 3 (and
thus helping provide information for this document and its various revisions
over the years):</p>
<ul class="simple">
<li><a class="reference external" href="http://wiki.python.org/moin/PortingPythonToPy3k">http://wiki.python.org/moin/PortingPythonToPy3k</a></li>
<li><a class="reference external" href="http://python3porting.com/">http://python3porting.com/</a></li>
<li><a class="reference external" href="http://docs.pythonsprints.com/python3_porting/py-porting.html">http://docs.pythonsprints.com/python3_porting/py-porting.html</a></li>
<li><a class="reference external" href="http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/">http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/</a></li>
<li><a class="reference external" href="http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html">http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html</a></li>
<li><a class="reference external" href="http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/">http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/</a></li>
<li><a class="reference external" href="http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/">http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/</a></li>
<li><a class="reference external" href="https://wiki.ubuntu.com/Python/3">https://wiki.ubuntu.com/Python/3</a></li>
</ul>
<p>If you feel there is something missing from this document that should be added,
please email the <a class="reference external" href="http://mail.python.org/mailman/listinfo/python-porting">python-porting</a> mailing list.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Porting Python 2 Code to Python 3</a><ul>
<li><a class="reference internal" href="#the-short-version">The Short Version</a></li>
<li><a class="reference internal" href="#before-you-begin">Before You Begin</a></li>
<li><a class="reference internal" href="#writing-source-compatible-python-2-3-code">Writing Source-Compatible Python 2/3 Code</a><ul>
<li><a class="reference internal" href="#projects-to-consider">Projects to Consider</a></li>
<li><a class="reference internal" href="#tips-tricks">Tips &amp; Tricks</a><ul>
<li><a class="reference internal" href="#support-python-2-7">Support Python 2.7</a></li>
<li><a class="reference internal" href="#try-to-support-python-2-6-and-newer-only">Try to Support Python 2.6 and Newer Only</a><ul>
<li><a class="reference internal" href="#from-future-import-print-function"><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">print_function</span></tt></a></li>
<li><a class="reference internal" href="#from-future-import-unicode-literals"><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">unicode_literals</span></tt></a></li>
<li><a class="reference internal" href="#bytes-string-literals">Bytes/string literals</a></li>
<li><a class="reference internal" href="#from-future-import-absolute-import"><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></tt></a></li>
</ul>
</li>
<li><a class="reference internal" href="#supporting-python-2-5-and-newer-only">Supporting Python 2.5 and Newer Only</a><ul>
<li><a class="reference internal" href="#id1"><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></tt></a></li>
<li><a class="reference internal" href="#mark-all-unicode-strings-with-a-u-prefix">Mark all Unicode strings with a <tt class="docutils literal"><span class="pre">u</span></tt> prefix</a></li>
<li><a class="reference internal" href="#capturing-the-currently-raised-exception">Capturing the Currently Raised Exception</a></li>
</ul>
</li>
<li><a class="reference internal" href="#handle-common-gotchas">Handle Common &#8220;Gotchas&#8221;</a><ul>
<li><a class="reference internal" href="#from-future-import-division"><tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></tt></a></li>
<li><a class="reference internal" href="#specify-when-opening-a-file-as-binary">Specify when opening a file as binary</a></li>
<li><a class="reference internal" href="#text-files">Text files</a></li>
<li><a class="reference internal" href="#subclass-object">Subclass <tt class="docutils literal"><span class="pre">object</span></tt></a></li>
<li><a class="reference internal" href="#deal-with-the-bytes-string-dichotomy">Deal With the Bytes/String Dichotomy</a><ul>
<li><a class="reference internal" href="#mark-up-python-2-string-literals">Mark Up Python 2 String Literals</a></li>
<li><a class="reference internal" href="#decide-what-apis-will-accept">Decide what APIs Will Accept</a></li>
<li><a class="reference internal" href="#bytes-unicode-comparison">Bytes / Unicode Comparison</a></li>
</ul>
</li>
<li><a class="reference internal" href="#indexing-bytes-objects">Indexing bytes objects</a></li>
<li><a class="reference internal" href="#str-unicode"><tt class="docutils literal"><span class="pre">__str__()</span></tt>/<tt class="docutils literal"><span class="pre">__unicode__()</span></tt></a></li>
<li><a class="reference internal" href="#don-t-index-on-exceptions">Don&#8217;t Index on Exceptions</a></li>
<li><a class="reference internal" href="#don-t-use-getslice-friends">Don&#8217;t use <tt class="docutils literal"><span class="pre">__getslice__</span></tt> &amp; Friends</a></li>
<li><a class="reference internal" href="#updating-doctests">Updating doctests</a></li>
<li><a class="reference internal" href="#update-map-for-imbalanced-input-sequences">Update <tt class="docutils literal"><span class="pre">map</span></tt> for imbalanced input sequences</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#eliminate-3-warnings">Eliminate <tt class="docutils literal"><span class="pre">-3</span></tt> Warnings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#alternative-approaches">Alternative Approaches</a><ul>
<li><a class="reference internal" href="#supporting-only-python-3-going-forward-from-python-2-code">Supporting Only Python 3 Going Forward From Python 2 Code</a></li>
<li><a class="reference internal" href="#backporting-python-3-code-to-python-2">Backporting Python 3 code to Python 2</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-resources">Other Resources</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Python HOWTOs</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cporting.html"
                        title="next chapter">Porting Extension Modules to Python 3</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/howto/pyporting.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python HOWTOs"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >Python HOWTOs</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2014, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jun 29, 2014.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>